package com.kingdee.zk.show;

import com.kingdee.pojo.ServerData;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * websocket 推送程序
 * @author 公众号：18岁fantasy
 * @date 2019年6月5日 下午4:19:22
 */
@ServerEndpoint("/ws/monitor")
public class WebSocketServer {

  private static Map<String, Session> clients = new HashMap<String, Session>();

  @OnOpen
  public void onOpen(Session session) throws IOException {

    clients.put(session.getId(), session);

    initDataToWeb();
  }

  /**
   * 初始化
   */
  public static void initDataToWeb() {
    sentDataToWeb(ServerMonitorListener.serverDatas);
  }

  static DecimalFormat df = new DecimalFormat("#.##");

  /**
   * 推送数据到浏览器
   * @param datas
   */
  public static void sentDataToWeb(List<ServerData> datas) {
    if (!clients.isEmpty() && !datas.isEmpty()) {
      StringBuffer buffer = new StringBuffer();
      buffer.append(
          "<table border=1 ><tr style='background-color:#999;'><td>服务器名称</td><td>cpu使用率</td><td>内存使用率</td><td>磁盘使用率</td></tr>");
      for (Iterator<ServerData> iterator = datas.iterator(); iterator.hasNext();) {
        ServerData serverData = (ServerData) iterator.next();
        String cpuAlarm =
            serverData.getCpuPercent() > ServerData.threshold ? "bgcolor=#ff0000;" : "";
        String memAlarm =
            serverData.getMemoryPercent() > ServerData.threshold ? "bgcolor=#ff0000;" : "";
        String diskAlarm =
            serverData.getDiskPercent() > ServerData.threshold ? "bgcolor=#ff0000;" : "";
        buffer.append("<tr>").append("<td>").append(serverData.getServerNodeName()).append("</td>")
            .append("<td " + cpuAlarm + ">").append(df.format(serverData.getCpuPercent()))
            .append("%</td>").append("<td " + memAlarm + ">")
            .append(df.format(serverData.getMemoryPercent())).append("%</td>")
            .append("<td " + diskAlarm + ">").append(df.format(serverData.getDiskPercent()))
            .append("%</td>");
        buffer.append("</tr>");
      }
      buffer.append("</table>");
      System.out.println("推送数据到浏览器：" + buffer.toString());
      for (Iterator<Session> iterator = clients.values().iterator(); iterator.hasNext();) {
        Session client = (Session) iterator.next();
        client.getAsyncRemote().sendText(buffer.toString());
      }
    }
  }

  @OnClose
  public void onClose(Session session) throws IOException {
    clients.remove(session.getId());
  }

}
